//
//  HttpManager.m
//  zaipin
//
//  Created by whj on 16/10/8.
//  Copyright © 2016年 master. All rights reserved.
//

#import "HttpManager.h"
#import <AFNetworking/AFNetworking.h>

@implementation HttpManager

+ (HttpManager *)shareManager
{
    static HttpManager *manager = nil;
    static dispatch_once_t singleManager;
    dispatch_once(&singleManager, ^{
        manager = [[self alloc] init];
    });
    return manager;
}
#pragma mark ---- 网络请求 POST 通用 ---
-(void)httpPOSTRequestWithPath:(NSString *)URLPath withDictionary:(NSDictionary  *)dict  success:(void (^)(HttpRequestBaseModel  *resultModel))success failure:(void (^)(NSError *error))failure{
    
 
    [self httpPost:URLPath params:dict success:^(id responsObject) {
        HttpRequestBaseModel *result = [HttpRequestBaseModel mj_objectWithKeyValues:responsObject];
        success(result);
    } failure:^(NSError *error) {
        failure(error);
    }];
}


#pragma mark ---- 网络请求 GET 通用 ---
-(void)httpGetRequestWithPath:(NSString *)URLPath withDictionary:(NSDictionary  *)dict  success:(void (^)(HttpRequestBaseModel  *resultModel))success failure:(void (^)(NSError *error))failure{
    [self httpGet:URLPath params:dict success:^(id responsObject) {
        HttpRequestBaseModel *result = [HttpRequestBaseModel mj_objectWithKeyValues:responsObject];
        success(result);
    } failure:^(NSError *error) {
        failure(error);
    }];
}



#pragma mark ----底层部分的几个重要的API---Http Common-----

#pragma mark  Get请求
/**
 *  Get请求
 *
 */
- (void)httpGet:(NSString *)URLString params:(id)params success:(void (^)(id responsObject) )success failure:(void (^)(NSError *error))failure
{
    NSLog(@"\n**************** 请求=路径 ****************\n");
    NSLog(@"\n%@\n",URLString);
    NSLog(@"\n**************** 请求=参数 ****************\n");
    NSLog(@"\n%@ ",params);
    
    [self.httpRequestSessionManager GET:URLString parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
        
        if (success) {
            success(responseObject);
        }
        NSLog(@"\n==========HTTP(s)-Success============\n");
        NSString *jsonStr = [responseObject mj_JSONString];
        //NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"\nreqUrl => %@  \n response---JSON ==>\n%@\n",URLString,jsonStr);
        NSLog(@"\n==========HTTP(s)-Success============\n");
        
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        
        NSLog(@"Request-GET--Error: %@", error);
        NSLog(@"\n==========HTTP(s)-Error============\n");
        NSLog(@"\nreqUrl => %@ error %@",URLString,error);
        NSLog(@"\n==========HTTP(s)-Error============\n");
        
        if (failure) {
            failure(error);
        }
    }];
}

#pragma mark  底层发送post
/**
 *  底层发送post
 *
 */
-(void)httpPost:(NSString *)URLString params:(id)params success:(void (^)(id responsObject))success failure:(void (^)(NSError *error))failure {
    
    NSLog(@"\n**************** 请求=路径 ****************\n");
    NSLog(@"%@",URLString);
    NSLog(@"\n**************** 请求=参数 ****************\n");
    NSLog(@"%@ ",params);
    
    [self.httpRequestSessionManager POST:URLString parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        //POST 的进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"响应的-->responseObject:\n%@", responseObject);
        
        if (success) {
            success(responseObject);
        }
        NSLog(@"\n==========HTTP(s)-Success============\n");
        NSString *jsonStr = [responseObject mj_JSONString];
        //        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        //        NSLog(@"response error str = %@",str);
        NSLog(@"\nreqUrl => %@  \n response---JSON ==> \n %@\n",URLString,jsonStr);
        NSLog(@"\n==========HTTP(s)-Success============\n");
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Request-POST--Error: %@", error);
        //        NSData *errorData = error.userInfo[NSUnderlyingErrorKey]
        NSLog(@"\n==========HTTP(s)-Error============\n");
        NSLog(@"\nreqUrl => %@ error %@",URLString,error);
        NSLog(@"\n==========HTTP(s)-Error============\n");
        if (failure) {
            failure(error);
        }
        
    }];
}

- (AFHTTPSessionManager *)httpRequestSessionManager
{
    static  AFHTTPSessionManager *manager = nil;
    static dispatch_once_t singleManager;
    dispatch_once(&singleManager, ^{
        manager = [AFHTTPSessionManager manager];
//        [manager setSecurityPolicy:[self securityPolicy]];
 
        AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
        [securityPolicy setAllowInvalidCertificates:YES];
        //这里进行设置；
        [manager setSecurityPolicy:securityPolicy];
        
        
        
//        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",nil];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        // manager.responseSerializer = [AFJSONResponseSerializer serializer];
    });

    return manager;
}




- (AFSecurityPolicy *)securityPolicy
{
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    //[AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];
    securityPolicy.allowInvalidCertificates = YES;
    return securityPolicy;
}

#pragma mark-公共参数
-(NSMutableDictionary *)publicParms{
    
    NSMutableDictionary *publicDict = [@{
                                         //                                         access_tokenKey:kCurrentAccount.access_token,
                                         //                                         scopeKey:kScope,
                                         //                                         stateKey:kState
                                         } mutableCopy];
    
    return publicDict;
}

#pragma mark -----图片上传----
- (void)httpUploadImages:(UIImage *)image
                     URL:(NSString *)URLPath
                   param:(NSDictionary *)dict
                 success:(void (^)(HttpRequestBaseModel  *resultModel))success
                 failure:(void (^)(NSError *))failure
{
    if (image == nil) {
        return;
    }
    

    [self.httpRequestSessionManager POST:URLPath parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *imageData = UIImageJPEGRepresentation(image,0.4);
        
        [formData appendPartWithFileData:imageData
                                    name:@"picture"
                                fileName:@"picture.jpg"
                                mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"上传进度==%f",uploadProgress.fractionCompleted);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"响应的-->responseObject:\n%@", responseObject);

        NSLog(@"\n==========HTTP(s)-Success============\n");
        NSString *jsonStr = [responseObject mj_JSONString];
        //        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        //        NSLog(@"response error str = %@",str);
        NSLog(@"\nreqUrl => %@  \n response---JSON ==> \n %@\n",URLPath,jsonStr);
        NSLog(@"\n==========HTTP(s)-Success============\n");
        
        HttpRequestBaseModel *httpBm = [HttpRequestBaseModel mj_objectWithKeyValues:responseObject];
        success(httpBm);
       
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
        NSLog(@"Request-POST--Error: %@", error);
        //        NSData *errorData = error.userInfo[NSUnderlyingErrorKey]
        NSLog(@"\n==========HTTP(s)-Error============\n");
        NSLog(@"\nreqUrl => %@ error %@",URLPath,error);
        NSLog(@"\n==========HTTP(s)-Error============\n");
        if (failure) {
            failure(error);
        }

    }];
}


@end
